import { createRouter, createWebHistory } from 'vue-router'
import AdminLayout from '../components/AdminLayout.vue'
import { getToken, checkAndRefreshToken, logout } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import '@/assets/css/nprogress.css'

// 配置NProgress
NProgress.configure({ 
  showSpinner: false, // 不显示加载圈
  minimum: 0.1, // 最小进度
  easing: 'ease', // 缓动函数
  speed: 500, // 动画速度
  trickleSpeed: 200 // 滴答速度
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/admin',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/auth/Login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/auth/Register.vue'),
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('../views/auth/ForgotPassword.vue'),
    },
    {
      path: '/reset-password',
      name: 'reset-password',
      component: () => import('../views/auth/ResetPassword.vue'),
    },

    {
      path: '/admin',
      component: AdminLayout,
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'admin-dashboard',
          component: () => import('../views/admin/Dashboard.vue'),
        },
        {
          path: 'users',
          name: 'admin-users',
          component: () => import('../views/user/UserManagement.vue'),
        },
        {
          path: 'roles',
          name: 'admin-roles',
          component: () => import('../views/role/RoleManagement.vue'),
        },
        {
          path: 'documents',
          name: 'admin-documents',
          component: () => import('../views/admin/DocumentManagement.vue'),
        },

        {
          path: 'system',
          name: 'admin-system',
          component: () => import('../views/admin/SystemManagement.vue'),
        },
        {
          path: 'permissions',
          name: 'admin-permissions',
          component: () => import('../views/permission/PermissionManagement.vue'),
        },
        {
          path: 'knowledge-bases',
          name: 'admin-knowledge-bases',
          component: () => import('../views/admin/KnowledgeBaseManagement.vue'),
        },
        {
          path: 'qa',
          name: 'admin-qa',
          component: () => import('../views/admin/QAManagement.vue'),
        },
        {
          path: 'vectors',
          name: 'admin-vectors',
          component: () => import('../views/admin/VectorManagement.vue'),
        },

        {
          path: 'profile',
          name: 'admin-profile',
          component: () => import('../views/user/PersonalInfo.vue'),
        },
      ],
    },
  ],
})


// 白名单（不需要登录的页面）
const whiteList = ['/login', '/register', '/forgot-password', '/reset-password']

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  const token = getToken()
  
  if (token) {
    // 已登录，访问登录页则跳转文档管理，否则放行
    if (to.path === '/login') {
      next('/admin/documents')
    } else {
      // 检查token是否即将过期，如果是则尝试刷新
      try {
        const isValid = await checkAndRefreshToken()
        if (isValid) {
          next()
        } else {
          // token无效，清除认证信息并跳转登录页
          logout()
          ElMessage.error('登录已过期，请重新登录')
          next('/login')
        }
      } catch (error) {
        console.error('Token validation failed:', error)
        logout()
        ElMessage.error('登录验证失败，请重新登录')
        next('/login')
      }
    }
  } else {
    // 未登录，访问白名单页面放行，否则跳转登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

// 路由后置守卫
router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

export default router
